//  DailyListView.swift
//  MM2
//
//  Created by 李成明 on 2022/1/1.


import UIKit
import MJRefresh

enum DailyListType {
    case personal(userId: Int)
    case follow
    case discover
}

class DailyListView: UIView {

    override init(frame: CGRect) {
        super.init(frame: CGRect.zero)
        
        NotificationCenter.default.addObserver(self, selector: #selector(notifiDailyChangeAction), name: NSNotification.Name(notifiDailyChange), object: nil)
        
        if let jsonStr = UserDefaults.standard.object(forKey: followDailyJson) as? String, let data = DailyListViewModel.deserialize(from: jsonStr) {
            self.dataSource.data.dailyList += data.data.dailyList
        }
        
        addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.edges.equalTo(self)
        }
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private var dataSource = DailyListViewModel()
    private var page = 1
    var listType: DailyListType = .follow
//    private var replyClick: ((DailyModel) -> Void)?
    
    weak var fatherVC: MViewController?
    
    private lazy var tableView: UITableView = {
        let view = UITableView()
        view.showsVerticalScrollIndicator = false
        view.showsHorizontalScrollIndicator = false
        view.estimatedRowHeight = 160
        view.rowHeight = UITableView.automaticDimension
        view.separatorStyle = .none
        view.delegate = self
        view.dataSource = self
        
        let header = MJRefreshNormalHeader.init(refreshingTarget: self, refreshingAction: #selector(tableViewHeaderAction))
        let footer = MJRefreshBackNormalFooter.init(refreshingTarget: self, refreshingAction: #selector(tableViewFooterAction))
        header.setTitle("", for: .pulling)
        header.setTitle("", for: .refreshing)
        header.setTitle("", for: .idle)
        header.lastUpdatedTimeLabel?.isHidden = true
        footer.setTitle("", for: .idle)
        footer.setTitle("", for: .pulling)
        footer.setTitle("", for: .refreshing)
        view.mj_header = header
        view.mj_footer = footer
        
        let footerView = UIView.init(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: kTabBarAndSafeH))
        view.tableFooterView = footerView
        
        
        view.register(DailyCell.self, forCellReuseIdentifier: "DailyCel")
        return view
    }()
}

extension DailyListView: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSource.data.dailyList.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "DailyCel", for: indexPath)
        if let cell = cell as? DailyCell {
            cell.model = dataSource.data.dailyList[safe: indexPath.row]
            cell.replyClick { [weak self] model in
                self?.replyClick(model: model)
            }.likeClick { [weak self] model,isLike in
                self?.likeClick(model: model, isLike: isLike)
            }.followClick { [weak self] model, isFollow in
                self?.followbtnClick(model: model, isFollow: isFollow)
            }.avatarClick { [weak self] model in
                self?.avatarClick(model: model)
            }
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        guard let model = dataSource.data.dailyList[safe: indexPath.row] else { return }
        detailClick(model: model)
    }
}

extension DailyListView {
    private func likeClick(model: DailyModel, isLike: Bool) {
        MoyaNetwork.request(target: BaseApi.likeDaily(dailyId: model.forumId, isLike: isLike)) { _, _ in }
    }
    
    private func replyClick(model: DailyModel) {
        print("回复")
    }
    
    private func avatarClick(model: DailyModel) {
        let vc = MineVC(userId: model.authorInfo.userId, hideTabbar: true)
        fatherVC?.navigationController?.pushViewController(vc, animated: true)
    }
    
    private func followbtnClick(model: DailyModel, isFollow: Bool) {
        MoyaNetwork.request(target: BaseApi.followSomeone(toUserId: model.authorInfo.userId, isFollow: isFollow)) {_,_ in }
    }
    
    private func detailClick(model: DailyModel) {
        let vc = DailyDetailVC(model: model)
        (fatherVC?.tabBarController as? MTabBarController)?.hidentabar()
        fatherVC?.navigationController?.pushViewController(vc, animated: true)
    }
    
    @objc private func tableViewHeaderAction() {
        dataSource.data.dailyList.removeAll()
        page = 1
        request()
    }
    
    @objc private func tableViewFooterAction() {
        page += 1
        request()
    }
    
    func beginRequest() {
        self.tableView.mj_header?.beginRefreshing()
        self.request()
    }
    
    private func request() {
        switch listType {
        case .personal(let userId):
            MoyaNetwork.request(target: BaseApi.perList(page: page, userId: userId)) { json, jsonStr in
                self.endRequest()
                guard let data = DailyListViewModel.deserialize(from: json.dictionaryObject) else { return }
                self.dataSource.data.dailyList += data.data.dailyList
                self.tableView.reloadData()
            }
        case .follow:
            MoyaNetwork.request(target: BaseApi.dailyList(isFollow: true, page: page)) { json, jsonStr in
                
                UserDefaults.standard.set(jsonStr, forKey: followDailyJson)
                UserDefaults.standard.synchronize()
                
                self.endRequest()
                guard let data = DailyListViewModel.deserialize(from: json.dictionaryObject) else { return }
                self.dataSource.data.dailyList += data.data.dailyList
                self.tableView.reloadData()
            }
        case .discover:
            MoyaNetwork.request(target: BaseApi.dailyList(isFollow: false, page: page)) { json, data in
                self.endRequest()
                guard let data = DailyListViewModel.deserialize(from: json.dictionaryObject) else { return }
                self.dataSource.data.dailyList += data.data.dailyList
                self.tableView.reloadData()
            }
        }
    }
    
    @objc private func notifiDailyChangeAction() {
        tableView.mj_header?.beginRefreshing()
        request()
    }
    
    private func endRequest() {
        self.tableView.mj_header?.endRefreshing()
        self.tableView.mj_footer?.endRefreshing()
    }
}
